from rest_framework.viewsets import ModelViewSet

from company.models import VehicleCompanyTerminal
from terminal.serializers import TerminalSerializer, TerminalParamsSerializer, TerminalControlSerializer, \
    TerminalCreateSerializer, TerminalListSerializer
from rest_framework.filters import SearchFilter
from terminal.models import Terminal, TerminalParams, TerminalControl


class IemiSearchFilters(SearchFilter):
    def filter_queryset(self, request, queryset, view):
        if request.query_params.get('search', "") == "":
            return queryset
        return super(IemiSearchFilters, self).filter_queryset(request, queryset, view)


class TerminalViewSet(ModelViewSet):
    """终端
    search=(终端号，SIM卡ICCID，车牌号)
    """
    queryset = Terminal.objects.all()
    filter_backends = [IemiSearchFilters]
    filter_fields = ('id', 'uid', 'iccid')
    search_fields = ('imei',)

    def get_serializer_class(self):
        if self.action == "create":
            return TerminalCreateSerializer
        elif self.action == "list":
            return TerminalListSerializer
        else:
            return TerminalSerializer

    def get_queryset(self):
        # 过滤出公司下的所有车辆安装的终端
        if self.action == "list":
            company = self.request.user.company
            terminal_ids = VehicleCompanyTerminal.objects.filter(company=company).values_list('terminal_id', flat=True)
            return Terminal.objects.filter(id__in=terminal_ids)
        return self.queryset


class TerminalParamsViewSet(ModelViewSet):
    queryset = TerminalParams.objects.all()
    serializer_class = TerminalParamsSerializer
    filter_fields = ('id',)


class TerminalControlViewSet(ModelViewSet):
    queryset = TerminalControl.objects.all()
    serializer_class = TerminalControlSerializer
